/**
 * Created by Weizehua on 2017/2/19.
 */
import {HandlerClass, Handle, ParamType, Require} from "../Core/Dispatcher/Dispatcher";
import {isLogged} from "../User/UserHandler";
import {Connection} from "typeorm";
import {FollowInfo} from "./FollowInfo";
import {User} from "../User/User";
import {RequestUserInfo} from "../Core/Dispatcher/Types";
import {UserInfo} from "../UserInfo/UserInfo";
@HandlerClass()
export class FollowInfoHandler {
    constructor(protected typeorm: Connection) {
    }

    @Handle('/follow/query')
    @ParamType({
        endId: Number,
    })
    @Require(isLogged)
    async queryFollow(userInfo: RequestUserInfo, param: any) {
        let users = await this.typeorm.entityManager
            .createQueryBuilder(UserInfo, "i")
            .innerJoin(FollowInfo, "f", "i.user = f.user")
            .where("f.follower = :follower", {follower: userInfo.id})
            .getMany();
        return {success: true, users: users};
    }

    @Handle('/follow/add')
    @ParamType({
        userId: Number,
    })
    @Require(isLogged)
    async addFollow(userInfo: RequestUserInfo, param: any) {
        let userId = param.userId;
        if (userInfo.id === userId)
            return "你一直在关注你自己，不用特地再关注了";
        let f = new FollowInfo();
        f.user = {id: userId} as User;
        f.follower = {id: userInfo.id} as User;

        await this.typeorm.entityManager
            .persist(f);
        return true;
    }

    @Handle('/follow/remove')
    @ParamType({
        userId: Number,
    })
    @Require(isLogged)
    async removeFollow(userInfo: RequestUserInfo, param: any) {
        let userId = param.userId;
        await this.typeorm.entityManager
            .createQueryBuilder(FollowInfo, 'fi')
            .delete()
            .where('user = :user')
            .andWhere('follower = :f')
            .setParameters({user: userId, f: userInfo.id})
            .execute();
        return true;
    }

}
